<?php
/*
 * 全局类 不依赖其他类或结构
 * 保持同步 eshop basic wxweb 
 */
class dbt_G extends sing_table {

    static $member_id;
    static $mid;
    /*
     * 直接返回json数据
     */
    function rJson($r = array()){
        if($_GET['callback'] && isset($r['Error'])){
            echo 'var data = '.json_encode($r).';';
            echo $_GET['callback'].'(data);';
        }else{
            $r['Error'] = $r['Error']?$r['Error']:0;
            $r['Msg'] = $r['Msg']?$r['Msg']:'操作成功';
            $r['data'] = $r['data']?$r['data']:array();
            echo json_encode($r);
        }

        exit;
    }

    /*
     * 自动添加必有字段 http://10.255.255.249/index.php/Home/item/show?page_id=146&item_id=10
     */
    function fetchBaseInsert($_mid,$data=array()){
        global $_G;
        $insertData = array();
        foreach($data as $k=>$v){
            $insertData[$k] = $v;
        }
        $insertData['_uid'] = isset($insertData['_uid'])?$insertData['_uid']:$_G['_uid'];
        $insertData['uid'] = isset($insertData['uid'])?$insertData['uid']:$_G['uid'];
        $insertData['mid'] = isset($insertData['mid'])?$insertData['mid']:$_mid;
        $insertData['inputtime'] = isset($insertData['inputtime'])?$insertData['inputtime']:TIME;
        $insertData['display'] = isset($insertData['display'])?$insertData['display']:1;
        return $insertData;
    }

    /*
     * 自动添加每次更新时必有字段
     */
    function fetchBaseUpdate($data=array()){
        $update = array();
        foreach($data as $k=>$v){
            $update[$k] = $v;
        }
        $update['updatetime'] = isset($update['updatetime'])?$update['updatetime']:TIME;
        return $update;
    }

    /*
     * 修改申请资料
     */
    function updFormDiy($data=array()){
        $arr = array();
        if($data){
            $data = json_encode($data);
        }
        return $data;
    }
    /*
     * 获取申请资料
     * type 1输入框    2文本域    3单选框    4复选框    5下拉框
     */
    function getFormDiy($data=array(),$parse=0){
        if($data){
            $data = json_decode($data,true);
            if($parse){
                foreach($data as $k => $v){
                    if($v['type']>2 && $v['option']){
                        $options = explode("\r\n", $v['option']);
                        $data[$k]['option'] = $options;
                    }
                }
            }
        }
        return $data;
    }

    /*
     * 格式化价格 存储之前使用
     */
    function beforePrice($price = 0){
        return $price * 100;
    }

    /*
     * 格式化价格 读取之后使用
     */
    function lastPrice($price = 0){
        return sprintf('%1.2f',$price/100);
    }

    /*
     * 保留两位小数
     */
    function float2($n = 0){
        return sprintf('%1.2f',$n);
    }

    function secondToWords($second){
        $day = $hour = $minute = 0;
    }
    
    //多条插入信息
    public function insertArr($table="",$arr=array()) {
        if(!$table || !is_array($arr)){
            return false;
        }
        
        $isFirst = true;
        
        $arrBoll = array();
        
        $strInsert = '';
        
        $sql = '';
        
        foreach($arr as $a){
            if(is_array($a)){
                $str = '';
                foreach($a as $k => $v){
                    if(is_array($v)){
                       return false; 
                    }
                    if($isFirst){
                        $arrBoll[$k] = true;
                        $strInsert .= $strInsert?','.DB::quote_field($k):DB::quote_field($k);
                    }else{
                        if(!$arrBoll[$k]){
                            return false;
                        }
                    }
                    $str .= $str?','.DB::quote($v):DB::quote($v);
                }
                $sql .= $isFirst?'('.$str.')':',('.$str.')';
                $isFirst = false;
            }else{
                return false;
            }
        }
        
        $format = DB::format("INSERT INTO %t(%i) VALUES%i", array($table,$strInsert,$sql));
        
        echo $format;
        
        $idArr= DB::query($format);
//        
//        DB::$_GetPk = false;
//        $idArr = DB::insert_id();
        
        return $idArr;
    }


    //获取 memberid  $force 强制获取 没有直接返回错误
    function fetchMemberId($mid,$member_id='',$openid='',$force=1)
    {
        if (!$member_id) {
            if (!$openid && $force) {
                C::t('G')->rJson(array('Error'=>1,'Msg'=>'会员身份不正确'));
            }else{
                DB::SetMainDB(DB_MAIN);
                $openid = DB::fetch_first('select openid,nickname,headimgurl from %t where mid=%s and openid=%s', array('wx_wxuser', $mid, $openid));
                if(!$openid['openid'] && $force){
                    C::t('G')->rJson(array('Error'=>1,'Msg'=>'会员身份不正确'));
                }
            }
            if($openid['openid']){
                DB::SetMainDB(DB_MAIN);
                $member_id = DB::result_first('select id from %t where mid=%s and openid=%s and display=1', array('common_member', $mid, $openid));
                if (!$member_id) {
                    $insert = array();
                    $insert['inputtime'] = TIME;
                    $insert['status'] = $insert['display'] = 1;
                    $insert['mid'] = $mid;
                    $insert['nickname'] = $openid['nickname'];
                    $insert['headimg'] = $openid['headimgurl'];
                    //$insert['clientip'] = $_G['clientip'];
                    $insert['openid'] = $openid['openid'];
                    DB::SetMainDB(DB_MAIN);
                    $member_id = DB::insert('common_member', $insert, true);

                    //可直接加复制基本微信会员信息程序 微信登录PC时 提示关联以后pc账号 或者新建（完成pc账号信息）
                }
            }

        }else{
            DB::SetMainDB(DB_MAIN);
            $member_id = DB::result_first('select id from %t where mid=%s and id=%d and display=1', array('common_member', $mid, $member_id));
            if(!$member_id  && $force){
                C::t('G')->rJson(array('Error'=>1,'Msg'=>'会员身份不正确'));
            }
        }
        self::$member_id = intval($member_id);
        return self::$member_id;
    }

    function fetchMemberBaseInfo($mid){
        if(!self::$member_id){
            return array();
        }
        DB::SetMainDB(DB_MAIN);
        $member = DB::fetch_first('select nickname,headimg from %t where mid=%s and id=%d and display=1', array('common_member', $mid, self::$member_id));
        return $member;
    }

    //获取基本表单结构
    function fetchBaseForm(){
        /*
         * 模块存储结构
        [
        {"type":"1","key":"name","must":"1","title":"姓名"},
        {"type":"1","key":"phone","must":"1","title":"电话"},
        {"type":"1","key":"qq","must":"1","title":"QQ"},
        {"type":"1","key":"company","must":"1","title":"单位"}
        ]
         */
        $form = json_decode('[
        {"type":"1","key":"name","title":"姓名"},
        {"type":"1","key":"phone","title":"电话"},
        {"type":"1","key":"qq","title":"QQ"},
        {"type":"1","key":"company","title":"单位"}
        ]',true);
        return $form;
    }

    //插入基本表单信息 contact表
    function inputBaseForm($mid,$openid,$type,$v){
        if(!$mid || !$openid || !$type || !$v){
            $this->rJson(array('Error'=>1,'Msg'=>'基本信息输入不正确'));
        }
        $contact = DB::fetch_first("select `id`,`usage` from %t where mid=%s and openid=%s and `type`=%s and d=%s and display=1",array("wx_contact",$mid,$openid,$type,trim($v)));
        if($contact){
            $usage = intval($contact['usage'])+1;
            DB::update("wx_contact", array("usage"=>$usage,"updatetime"=>TIME), array("id"=>$contact['id']));
        }else{
            DB::insert("wx_contact", array("type"=>$type,"d"=>trim($v),"inputtime"=>TIME,"display"=>1,"mid"=>$mid,"openid"=>$openid,"usage"=>0));
        }
    }


    //基本表单 获取输出值
    function outputBaseForm($mid,$openid,$type){
        if(!$mid || !$openid || !$type){
            $this->rJson(array('Error'=>1,'Msg'=>'基本信息输出不正确'));
        }
        $val = DB::result_first("select `d` from %t where mid=%s and openid=%s and `type`=%s and display=1 order by `usage` desc",array("wx_contact",$mid,$openid,$type));
        return $val;
    }
}